class Solution:
    def candy(self, ratings: list) -> int:
        queue = []
        for i in range(len(ratings)):
            queue.append((i, ratings[i]))
        queue = [item[0] for item in sorted(queue, key=lambda item: item[1])]
        candies = [0 for _ in range(len(ratings))]
        for i in queue:
            left = 0
            right = 0
            if i - 1 >= 0 and ratings[i - 1] != ratings[i]:
                left = candies[i - 1]
            if i + 1 < len(ratings) and ratings[i + 1] != ratings[i]:
                right = candies[i + 1]
            candies[i] = max(left, right) + 1

        return sum(candies)
